/* 
操作数据模块 API
*/

const fs = require('fs')
const db = './public/json/studys.json'
// 获取所有学生列表
exports.find = (callback) => {
    fs.readFile(db, (err, data) => {
        if (err) {
            callback(err)
            return
        }
        callback(null, JSON.parse(data).studys)
    })
}
//根据ID获取单个学生
exports.findID = (id, callback) => {
    fs.readFile(db, (err, data) => {
        if (err) {
            callback(err)
            return
        }
        let ret = JSON.parse(data).studys.find(item => item.id === parseInt(id))
        callback(null, ret)
    })
}
// 增加学生
exports.save = (student, callback) => {
    fs.readFile(db, (err, data) => {
        if (err) {
            callback(err)
            return
        }
        var students = JSON.parse(data).studys
        student.id = students[students.length - 1].id + 1
        students.push(student)
        var ret = JSON.stringify({ studys: students })
        fs.writeFile(db, ret, err => {
            if (err) {
                console.log('1');
                callback(err)
                return
            }
            callback(null)
        })
    })
}
// 更新学生
exports.updataID = (student, callback) => {
    fs.readFile(db, (err, data) => {
        if (err) {
            return callback(err)
        }
        // 找出需要需改 学生的信息
        var students = JSON.parse(data).studys
        student.id = parseInt(student.id)
        let stu = students.find(item => item.id === student.id)
        for (let key in student) {
            stu[key] = student[key]
        }
        let fileData = JSON.stringify({ studys: students })
        fs.writeFile(db, fileData, err => {
            if (err) {
                callback(err)
                return
            }
            callback(null)
        })
    })

}

// 删除学生
exports.deletedId = (id, callback) => {
    fs.readFile(db, (err, data) => {
        if (err) {
            callback(err)
            return
        }
        var students = JSON.parse(data).studys
        let deleteId = students.findIndex(function (item) {
            return item.id === parseInt(id)
        })
        console.log('shanchu');
        console.log(deleteId);
        students.splice(deleteId, 1)
        //转为字符串,并且保存
        var ret = JSON.stringify({ studys: students })
        fs.writeFile(db, ret, err => {
            if (err) {
                console.log('1');
                callback(err)
                return
            }
            callback(null)
        })
    })

}
